package com.situ.scientific.filter;



import com.situ.scientific.pojo.Auth;
import com.situ.scientific.pojo.Researchers;
import com.situ.scientific.service.IAuthService;
import com.situ.scientific.service.IResearchersService;
import com.situ.scientific.service.impl.AuthserviceImpl;
import com.situ.scientific.service.impl.ResearchersServiceImpl;
import com.situ.scientific.util.CookieUtil;
import com.situ.scientific.util.JSONUtil;
import com.situ.scientific.util.Result;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

// /*代表拦截所有请求
@WebFilter(filterName = "login", urlPatterns = "/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("LoginFilter.init");
    }

    //service
    // ServletRequest servletRequest = new HttpServletRequest()
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("LoginFilter.doFilter");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String uri = request.getRequestURI();
        System.out.println("uri: " + uri);
        //uri: /static/layui/layui.js
        //uri: /static/layui/css/layui.css
        //uri: /static/layui/font/iconfont.woff2
        String method = request.getParameter("method");
        System.out.println("method: " + method);
        //如果这个请求是要去完成登录的，不需要执行后面的验证是否已经登录的流程
        //这些是没有登录情况下可以访问的资源
        if (uri.startsWith("/static")  // 访问/static都放行
                || uri.equals("/page/login")
                || uri.equals("/verifyCode")
                || (uri.equals("/researchers") && "login".equals(method))) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        //如果session还在的话，就直接登录
        HttpSession session = request.getSession();
        Researchers researchers = (Researchers) session.getAttribute("researchers");
        if (researchers == null) {//如果session失效了，就检查一下有没有cookie
            Cookie cookie = CookieUtil.getCookie(request,"autoLogin");
            if(cookie != null){//如果cookie不为null，将执行下面的代码
                //现在的情况是，researchers == null， but cookie ！= null ，that means the session is invalid and there has
                // a cookie on the browser, so just skip the servlet go directly to the service login method
                String[] cookies = cookie.getValue().split("&");
                String name = cookies[0];
                String password = cookies[1];
                IResearchersService researchersService = new ResearchersServiceImpl();
                researchers = researchersService.login(name, password);
                IAuthService authService = new AuthserviceImpl();
                if (researchers != null){
                    session.setAttribute("researchers", researchers);
                    List<Auth> authList = authService.selectByRole(researchers.getRole());
                    session.setAttribute("authList",authList);
                    JSONUtil.toJSON(response, Result.ok("登录成功"));
                    filterChain.doFilter(servletRequest, servletResponse);
                    return;
                }
            }
            response.sendRedirect("/page/login");
            return;
        }

        //user这个令牌不是null，用户已经登录
        //如果加了这了这句话代表放行，继续往后执行
        //1.如果后面还有filter就访问后面的filter 2.没有filter就访问后台资源
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println("LoginFilter.destroy");
    }
}
